package com.cd.system.jpa.repository;

import com.cd.system.jpa.entity.Product;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository("LqqProductDao")
@Transactional
public interface ProductRepository extends CrudRepository<Product, Long> {

    @Query(value = "SELECT * FROM lqqdb_product WHERE id=?1", nativeQuery = true)
    Product findByProductId(Long productId);

    @Modifying
    //@Query(value = "UPDATE lqqdb_product SET stock = CASE WHEN stock >0 THEN stock-1 ELSE stock END WHERE id=?1", nativeQuery = true)
    //楼上写法会导致超卖
    @Query(value = "update lqqdb_product set stock=stock-1 where id=?1 and stock>0",nativeQuery = true)
    int updateByProductId(Long productId);
}
